package one.stand.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
public class IOUtil {
    public static String stream2String(InputStream inputStream) {
        if (Objects.isNull(inputStream)) return null;

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        try {
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            return result.toString("UTF-8");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                result.close();
                buffer = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

//    public static String out2String(OutputStream inputStream) {
//        if (Objects.isNull(inputStream)) return null;
//
//        ByteArrayOutputStream result = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int length;
//        try {
//            while ((length = inputStream.(buffer)) != -1) {
//                result.write(buffer, 0, length);
//            }
//            return result.toString("UTF-8");
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//        } finally {
//            try {
//                result.close();
//                buffer = null;
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
}
